<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class AdminProductImageController extends Controller
{
    public function index(Product $product)
    {
        return response()->json([
            'images' => $product->images()->orderBy('sort_order')->get(),
        ]);
    }

    public function store(Request $request, Product $product)
    {
        $request->validate([
            'image' => 'required|image|max:5120', // 5MB
            'alt_text' => 'nullable|string|max:255',
            'title' => 'nullable|string|max:255',
        ]);

        $file = $request->file('image');
        $dir = 'products/'.date('Y/m');
        $filename = Str::uuid()->toString().'.'.$file->getClientOriginalExtension();
        $path = $file->storeAs($dir, $filename, 'public');

        $image = $product->images()->create([
            'image_path' => '/storage/'.$path,
            'alt_text' => $request->input('alt_text'),
            'title' => $request->input('title'),
            'sort_order' => ($product->images()->max('sort_order') ?? 0) + 10,
            'is_primary' => $product->images()->doesntExist(),
        ]);

        // Inertia 文件上传推荐返回重定向
        return redirect()->back()->with('success', '图片已上传');
    }

    public function destroy(Product $product, ProductImage $image)
    {
        if ($image->product_id !== $product->id) {
            abort(404);
        }

        // 删除文件
        if ($image->image_path) {
            $relative = ltrim(str_replace('/storage/', '', $image->image_path), '/');
            Storage::disk('public')->delete($relative);
        }

        $image->delete();

        return response()->json(['success' => true]);
    }

    public function setPrimary(Product $product, ProductImage $image)
    {
        if ($image->product_id !== $product->id) {
            abort(404);
        }

        $product->images()->update(['is_primary' => false]);
        $image->update(['is_primary' => true]);

        return response()->json(['success' => true]);
    }

    public function sort(Request $request, Product $product)
    {
        $request->validate([
            'orders' => 'required|array', // [image_id => sort_order]
        ]);

        foreach ($request->input('orders') as $id => $order) {
            $product->images()->where('id', $id)->update(['sort_order' => (int) $order]);
        }

        return response()->json(['success' => true]);
    }
}


